#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int connect_to_server(){
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in serv_addr;
    int len;
    memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
    serv_addr.sin_family = AF_INET;  //使用IPv4地址
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  //具体的IP地址
    serv_addr.sin_port = htons(54321);  //端口
    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        printf("can not connect to server.\n");
        return 0;
    }

    char buffer[40] = {'h', 'e', 'l', 'l', 'o', 0};

    errno = 0;
    len = write(sock, buffer, 5);
    len = read(sock, buffer, len);

    if (len < 0) {
        printf("%d\n", errno);
    }
    else {
        printf("len is %d\n", len);
        buffer[len] = '\0';
        printf("recv: %s\n", buffer);
    }
}

int main() {
    int i;
    pid_t pid;
    for (i = 0; i < 2; i++) {
        if (!(pid = fork())) {
            connect_to_server();
            exit(0);
        }
        else {
            wait(pid);
        }
    }
    return 0;
}

